import { getSearchHot, getSearchSuggest, getSearchResult } from '../../../service/api_search'
import { debounce } from '../../../utils/debounce'
import { stringToNodes } from '../../../utils/string-to-nodes'
const debounceFn = debounce(getSearchSuggest)
Page({
	data: {
		hotKeywords: [],
		keyword: '',
		suggestSongs: [],
		suggestSongsNodes: [],
		resultSongs: []
	},
	onLoad: function () {
		// 获取页面数据
		this.getpageData()
	},
	// 点击热门搜索的每个item 
	handleHotKeyWordClick(event) {
		const item = event.currentTarget.dataset.item;
		this.setData({ keyword: item })
		this.handleSearchAction()
	},
	// 输入完成,点击enter键进行搜索
	handleSearchAction() {
		const keyword = this.data.keyword
		if(!keyword) return
		getSearchResult(keyword).then(res => {
			this.setData({ resultSongs: res.result.songs })
		})
	},
	// 搜索弹出的item进行点击
	searchItemClick(event){
		// 点击的关键字
		const index = event.currentTarget.dataset.index;
		const keyword = this.data.suggestSongs[index].keyword
		// 将关键字放在搜索框中
		this.setData({ keyword })
		// 发送网络请求
		this.handleSearchAction()
	},
	// 网络请求
	getpageData(){
		getSearchHot().then(res => {
			this.setData({ hotKeywords: res.result.hots })
		})
	},
	// 输入内容变化时触发
	handleSearchChange(event) {
		this.setData({ keyword: event.detail })
		if(!event.detail) {
			this.setData({ suggestSongs: [], suggestSongsNodes: [], resultSongs: [], suggestSongsNodes: [] })
			return
		}
		debounceFn(event.detail).then(res => {
			// 获取关键字歌曲
			const suggestSongs = res.result.allMatch
			this.setData({ suggestSongs })

			// 转为富文本的nodes
			const suggestKeyWords = suggestSongs.map(item => item.keyword)
			const suggestSongsNodes = []
			suggestKeyWords.forEach(keyword => {
				// stringToNodes封装的字符串转节点方法
				const nodes = stringToNodes(keyword, event.detail)
				suggestSongsNodes.push(nodes)
			});
			this.setData({ suggestSongsNodes })
		})
	}
})
